package com.ytktt.study.week9.task7.account.service;

import com.ytktt.study.week9.task7.account.mapper.AccountMapper;
import com.ytktt.study.week9.task7.account.mapper.FreezeAmountMapper;
import com.ytktt.study.week9.task7.account.api.Account1Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 账户1业务逻辑实现
 *
 * @author ytk
 */
@Slf4j
@Service("account1Service")
@RequiredArgsConstructor
public class Account1ServiceImpl implements Account1Service {

    private final AccountMapper accountMapper;
    private final FreezeAmountMapper freezeAmountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @HmilyTCC(confirmMethod = "confirm", cancelMethod = "cancel")
    public boolean exchangeCNYToUSD() {
        int result = this.accountMapper.update(7, 2, 0);
        if (result == 1) {
            int update = this.freezeAmountMapper.update(1, 7);
            if (update == 1) {
                return true;
            } else {
                throw new IllegalArgumentException("账户扣减异常");
            }
        } else {
            throw new IllegalArgumentException("账户扣减异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @HmilyTCC(confirmMethod = "confirm", cancelMethod = "cancel")
    public boolean mockExchangeCNYToUSDTryException() {
        int result = this.accountMapper.update(7, 2, 0);
        throw new IllegalArgumentException("账户扣减异常");
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean confirm() {
        log.info("============dubbo tcc 执行确认付款接口===============");
        this.accountMapper.updateConfirm(1, 2, 1);
        this.freezeAmountMapper.updateConfirm(1, 7);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean cancel() {
        log.info("============ dubbo tcc 执行取消付款接口===============");
        this.accountMapper.updateCancel(7, 2, 0);
        this.freezeAmountMapper.updateCancel(1, 7);
        return true;
    }
}
